package com.wxy.care.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;

import com.wxy.care.entity.Count;
import com.wxy.care.service.CountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@Async
public class TcpServer {

    @Value("${server.socket.port}") // 通过配置文件获取端口号
    private int port;

    @Autowired
    private CountService countService;
    public void startServer() {
        try {
            ServerSocket serverSocket = new ServerSocket(port); // 创建服务器Socket对象
            System.out.println("服务器已启动，等待客户端连接...");

            while (true) {
                Socket socket = serverSocket.accept(); // 等待客户端连接
                System.out.println("客户端已连接：" + socket.getInetAddress().getHostName());
                // 开启一个新的线程处理客户端的请求

                new Thread(() -> {
                    try {
                        InputStream inputStream = socket.getInputStream();
                        byte[] buffer = new byte[1024];
                        int length;

                        // 循环读取客户端发送的数据
                        while ((length = inputStream.read(buffer)) != -1) {
                            String message = new String(buffer, 0, length);
//                            System.out.println("接收到客户端消息：" + message);
                            int i = message.indexOf(',');
                            String houseName = message.substring(0,i).replaceAll("\\s","");
                            String slaveId = message.substring(i + 1).replaceAll("\\s","");
                            Count count = new Count();
                            count.setHouseName(houseName);
                            count.setSlaveId(slaveId);
                            count.setDate(LocalDateTime.now());
                            try {
                                countService.save(count);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }


                        inputStream.close();
                        socket.close();
                    } catch (IOException e) {
                        System.out.println("错误处理逻辑：" + e.getMessage());
                    }
                }).start();
            }
        } catch (IOException e) {
            System.out.println("错误处理逻辑：" + e.getMessage());
        }
    }
}
